<script>
import WangEditor from '@/components/WangEditor/index.vue'
import { dictMixin } from '@/mixin/dict'

export default {
  name: 'OperateAIModel',
  components: { WangEditor },
  mixins: [dictMixin],
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      projectList: [],
      runningModeList: [],
      fileList: [],
      formData: {}
    }
  },
  created() {
    this.$api.commonSelected({
      code: 'SceneProjectSelected'
    }).then(response => {
      this.projectList = response.data
    })
    this.$api.commonSelected({
      code: 'AIModelRunningModeSelected'
    }).then(response => {
      this.runningModeList = response.data
    })
  },
  computed: {
    rules() {
      return {
        modelName: [
          { required: true, message: '请输入模型名称' },
          { max: 100, message: '模型名称最长100字符' }
        ],
        sceneProjectId: [{ required: true, message: '请选择所属项目', trigger: 'blur' }],
        runningMode: [{ required: true, message: '请选择运行模式', trigger: 'blur' }],
        remarkText: [{ required: true, trigger: 'blur', validator: this.remarkValidate }]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        this.isAdd = !data.id
        this.formData = Object.assign({}, data)
        if (data.images != null) {
          const imageArray = JSON.parse(data.images)
          imageArray.forEach((item) => {
            this.fileList.push({
              url: item.url
            })
          })
        }
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      this.submit(params)
    }
  },
  methods: {
    remarkValidate(rule, value, callback) {
      if (this.fileList.length > 0 && this.formData.remarkText?.length > 50) {
        callback('项目介绍不超过50字')
        return
      } else if (this.formData.remarkText?.length > 200) {
        callback('项目介绍不超过200字')
        return
      }
      callback()
    },
    editorChange(value, text) {
      console.log('ai-model remark change: ', value, text, text?.length)
      this.formData.remark = value
      this.formData.remarkText = text
      this.$refs.form.validateField(['remarkText'], (errorMessage) => {
      })
    },
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    handleRemoveChange(file, fileList) {
      this.fileList = fileList
    },
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.fileList.length > 0) {
            const files = []
            for (const item of this.fileList) {
              if (item.raw) {
                const formData = new FormData()
                formData.append('file', item.raw)
                const urlRes = await this.$api.fileManage.baseUploadData(
                  '/energy-carbon/grass-file/file/upload',
                  formData
                )
                files.push({ url: urlRes.data })
              } else {
                files.push({ url: item.url })
              }
            }
            params.images = JSON.stringify(files)
          } else {
            params.images = null
          }
          delete params.createTm
          delete params.createBy
          delete params.modifyTm
          delete params.remarkText
          params.remark = this.formData.remark
          const res = await this.$api.aiModel[this.isAdd ? 'add' : 'update'](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'operate-aimodel-add')
          }
        }
      })
    }
  }
}
</script>

<template>
  <div class="ai-model-box">
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="AI模型名称" prop="modelName">
        <el-input v-model="formData.modelName" placeholder="请输入模型名称" style="width: 50%" />
      </el-form-item>
      <el-form-item label="所属项目" prop="sceneProjectId">
        <el-select v-model="formData.sceneProjectId" placeholder="请选择所属项目" style="width: 50%">
          <el-option v-for="item in projectList" :key="item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="AI模型介绍" prop="remarkText">
        <WangEditor v-model="formData.remarkText" @editorChange="editorChange" :default-value="this.formData.remark" />
      </el-form-item>
      <el-form-item label="AI模型图片" prop="images">
        <el-upload
          ref="upload"
          list-type="picture-card"
          action=""
          :on-change="handleChange"
          :on-remove="handleRemoveChange"
          :file-list="fileList"
          :auto-upload="false"
          :limit="4"
          accept="image/*"
        >
          <i class="el-icon-plus" />
          <div slot="tip" class="el-upload__tip">
            <span>图片不超过4张，请上传jpg/png文件，且不超过5MB,建议尺寸500px * 100px </span>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="运行模式" prop="runningMode">
        <el-radio v-model="formData.runningMode" v-for="item in runningModeList" :key="item.value"
                  :label="item.value">{{ item.label }}
        </el-radio>
      </el-form-item>
    </el-form>
  </div>
</template>
